package cn.bass.marketing.service.strategyRule.impl;

import cn.bass.marketing.common.constant.RedisConstant;
import cn.bass.marketing.common.constant.RulesConstant;
import cn.bass.marketing.common.enums.StatusEnums;
import cn.bass.marketing.common.exception.AppException;
import cn.bass.marketing.common.vo.resp.MarketingStrategyRuleRespVO;
import cn.bass.marketing.convertor.MarketingStrategyRuleConvertor;
import cn.bass.marketing.entity.MarketingStrategyRuleDO;
import cn.bass.marketing.mapper.MarketingStrategyRuleMapper;
import cn.bass.marketing.redis.core.IRedisService;
import cn.bass.marketing.service.strategyRule.MarketingStrategyRuleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;


/**
 * {@author}: LiuWei
 * {@version}: 1.0
 * {@since}: 2024-08-15
 * 描述：策略规则接口实现类
 */
@Slf4j
@Service
public class MarketingStrategyRuleServiceImpl extends ServiceImpl<MarketingStrategyRuleMapper, MarketingStrategyRuleDO> implements MarketingStrategyRuleService {

    @Resource
    private IRedisService redisService;

    @Override
    public MarketingStrategyRuleRespVO selectByStrategyIdAndRuleModel(String strategyId, RulesConstant ruleBlacklistKey) {
        String redisKey = String.format(RedisConstant.STRATEGY_RULE_KEY, strategyId);
        MarketingStrategyRuleRespVO cacheStrategyRuleRespVO = redisService.getValue(redisKey);
        if (Objects.nonNull(cacheStrategyRuleRespVO)) {
            log.info("命中缓存，策略ID：{},规则模型：{}", strategyId, ruleBlacklistKey);
            return cacheStrategyRuleRespVO;
        }
        // 查询策略规则
        LambdaQueryWrapper<MarketingStrategyRuleDO> strategyRuleWrapper = Wrappers.lambdaQuery();
        strategyRuleWrapper.eq(MarketingStrategyRuleDO::getCStrategyId, strategyId);
        strategyRuleWrapper.eq(MarketingStrategyRuleDO::getCRuleModels, ruleBlacklistKey);
        strategyRuleWrapper.eq(MarketingStrategyRuleDO::getCStatus, StatusEnums.ENABLED.getStatusType());
        strategyRuleWrapper.last("LIMIT 1");
        MarketingStrategyRuleDO marketingStrategyRuleDO = this.baseMapper.selectOne(strategyRuleWrapper);
        if (Objects.isNull(marketingStrategyRuleDO)) {
            log.error("策略规则不存在，策略ID：{},规则模型：{}", strategyId, ruleBlacklistKey);
            throw new AppException("策略规则不存在");
        }
        MarketingStrategyRuleRespVO marketingStrategyRuleRespVO = MarketingStrategyRuleConvertor.INSTANCE.do2RespVO(marketingStrategyRuleDO);
        redisService.setValue(redisKey, marketingStrategyRuleRespVO);
        return marketingStrategyRuleRespVO;
    }
}
